<template>
<!--
* @Author: liuzehai
* @Motto: 求知若渴,虚心若愚
 * @LastEditTime: 2021-08-11 14:20:04
* @Description: 账号管理
 * @FilePath: /basic-services/src/views/account/account.vue
-->
  <div class="app-container">
    <div class="filter-container">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input class="filter-item" v-model="listQuery.name" placeholder="请输入姓名" clearable></el-input>
        </el-col>
        <el-col :span="6">
          <el-input class="filter-item" v-model="listQuery.username" placeholder="请输入账户名称" clearable></el-input>
        </el-col>
        <el-col :span="6">
          <el-select class="filter-item" v-model="listQuery.usable" placeholder="请选择状态" clearable>
            <el-option label="启用" :value="1"/>
            <el-option label="禁用" :value="0"/>
          </el-select>
        </el-col>
        <el-col :span="6" class="filter-btn-col">
          <el-button type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
          <el-button type="primary" icon="el-icon-edit" v-permission="{code: 'base:account:add'}" @click="addaccount">新增</el-button>
        </el-col>
      </el-row>
    </div>
       <div class="table">
       <el-table
        :data="tableData"
        border
        style="width: 100%">
          <el-table-column
          prop="name"
          label="姓名"
          width="150">
        </el-table-column>
         <el-table-column label="所属角色" align="center" width="400">
          <template v-slot="{ row }">
             <el-tag class="role-name-tag" size="mini" v-for="item in row.roles" :key="'roles'+item.roleName" v-text="item.roleName" />
          </template>
        </el-table-column>
         <el-table-column
          prop="username"
          label="账户名称"
          width="150">
        </el-table-column>
         <el-table-column
          prop="deptName"
          label="所在省市县(区)"
          width="150">
        </el-table-column>
         <el-table-column label="状态" align="center" width="75">
          <template v-slot="{ row }">
             <span>{{ row.usable == 1 ? "启用" : "禁用" }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间" width="160">
        </el-table-column>
         <el-table-column
          prop="modifyTime"
          label="变更时间" width="160">
        </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding"
        width="320"
        fixed="right"
      >
        <template v-slot="scope">
          <div class="btnnuma">
            <el-button type="primary" size="small" v-permission="{code: 'base:account:update'}" @click="Modify(scope.row,1)">修改</el-button>
            <el-button type="danger" size="small" v-permission="{code: 'base:account:delete'}" @click="deleteButton(scope.row)">删除</el-button>
            <el-button type="warning" size="small" @click="disablebtn(scope.row)">{{scope.row.usable == '1' ? '禁用':'启用'}}</el-button>
            <el-button type="success" size="small" @click="resetButton(scope.row)">重置密码</el-button>
          </div>
                </template>
      </el-table-column>
      </el-table>
      <pagination
        :total="totalElements"
        :page.sync="page.pageNumber"
        :limit.sync="page.pageSize"
        @pagination="getList"
      />
    </div>
    <el-dialog
      center
      :title="updateTitle"
      width="60%"
      top="10vh"
      :visible.sync="dialogCarInfoVisible">
      <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="140px">
        <el-row>
          <el-col :span="22">
            <el-form-item prop="name" label="姓名">
              <el-input size="small" :maxlength="30" placeholder="请输入姓名" v-model="ruleForm.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="22">
            <el-form-item prop="usable" label="状态"> <el-select v-model="ruleForm.usable" placeholder="请选择状态">
              <el-option label="启用" value="1"></el-option>
              <el-option label="禁用" value="0"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="22">
          <el-form-item prop="username" label="账号">
            <el-input size="small" :disabled="AccountUpdat" :maxlength="30" placeholder="账号" v-model="ruleForm.username"></el-input>
            </el-form-item>
          </el-col>
           <el-col v-if="typeRole==0" :span="22">
            <el-form-item prop="password" label="密码">
              <el-input size="small" placeholder="密码" v-model="ruleForm.password"></el-input>
            </el-form-item>
          </el-col>
           <el-col :span="22">
          <el-form-item prop="username" label="角色">
            <el-select v-model="ruleForm.roleIds" multiple placeholder="请选择角色">
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id">
              </el-option>
            </el-select>
            </el-form-item>
          </el-col>
           <el-col :span="22">
          <el-form-item prop="deptId" label="所属机构">
            <el-cascader filterable style="width: 40%;" popper-class="cascaderClass" :options="lists" v-model="ruleForm.deptId" :show-all-levels='false' :props="{ checkStrictly: true,label:'deptName',value:'id' }" clearable></el-cascader>
            </el-form-item>
          </el-col>
           <!-- <el-col :span="22">
          <el-form-item prop="phone" label="手机号">
            <el-input size="small" :maxlength="11" placeholder="手机号" v-model="ruleForm.phone"></el-input>
            </el-form-item>
          </el-col>
           <el-col :span="22">
          <el-form-item prop="idCard" label="身份证号">
            <el-input size="small" :maxlength="18" placeholder="身份证号" v-model="ruleForm.idCard"></el-input>
            </el-form-item>
          </el-col>
           <el-col :span="22">
          <el-form-item prop="email" label="邮箱">
            <el-input size="small" :maxlength="30" placeholder="邮箱" v-model="ruleForm.email"></el-input>
            </el-form-item>
          </el-col>
           <el-col :span="22">
              <el-form-item prop="" label="性别">
              <el-radio v-model="ruleForm.gender" label="1">男</el-radio>
              <el-radio v-model="ruleForm.gender" label="2">女</el-radio>
              </el-form-item>
          </el-col>
            <el-col :span="22">
          <el-form-item prop="" label="头像">
            <el-upload action='' :on-change="getFile" :file-list="fileList" :limit="1" list-type="picture" :auto-upload="false">
              <el-button size="small" type="primary">{{picture}}</el-button>
              <div slot="tip" class="el-upload__tip">只能上传JPG/PNG/JPEG，且不超过1MB</div>
            </el-upload>
             <div class="userImg" v-if="pictureShow"><img :src="userPhoto" class="avatar"></div>
            </el-form-item>
          </el-col> -->
       </el-row>
      </el-form>
       <span slot="footer" class="dialog-footer">
          <el-button @click="dialogCarInfoVisible = false">取 消</el-button>
          <el-button type="primary" @click="onSubmit">保存</el-button>
        </span>
    </el-dialog>
    <el-dialog
      title="重置密码"
      :visible.sync="centerDialogVisible"
      width="30%"
      center>
      <span>重置密码,该账号可用初始密码登陆</span>
      <span>初始密码123456</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="resetBut">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from "@/components/Pagination";
import { account, role } from "@/api/account";
import { getMechanismList } from "@/api/resource";
import crypto from "@/utils/crypto";
import arrayToTree from "array-to-tree"

export default {
  name: "account",
  components: { 
    Pagination
   },
  data() {
    return {
      tableData: [],
      totalElements: 0,
      roleList: [], //角色列表
      fileList:[], //上传文件的列表
      props: {
        label: "name",
        children: "children",
      },
       defaultProp:{
        label: 'deptName',
        id:'id',
        parentId:'parentId'
    },
      centerDialogVisible: false,
      updateTitle: "增加用户",
      typeRole: 0, //判断新增还是修改角色
      scopeId: "",
      listQuery: {  //数据列表表单
        deptId:"",
        name: "",
        usable: "",
        username: "",
        userId:this.sessionData("get","userId"),
        //tenantId: this.sessionData("get","tenantId")
      },
      page: {
        pageNumber: 1,
        pageSize: 10,
      },
      dialogCarInfoVisible: false,
      deptId:"",//以外的机构第
      department:"",
      userPhoto:"",//用户头像
      picture:"上传头像",//
      pictureShow: false,
      ruleForm: {
        name: "", //姓名
        username: "", //账号
        roleIds: [], //角色id
        usable: "", //启用状态
        deptId: "", //机构id
        //tenantId: this.sessionData("get","tenantId"),
        phone:"", //手机号
        email:"",//邮箱
        idCard:"",//身份证号
        photo:"",//头像base64编码
        gender:"", //性别
        password:"",
      },
      lists: [], //资源树列表
      menuIds: [],
      jueseId: "", //用户id
      AccountUpdat:false,
      parentId:"",
      rules: {
        name: [
          { required: true, message: "请输入员工姓名", trigger: "blur" },
          { min: 1, max: 30, message: "长度在 1 到 30 个字符", trigger: "blur" },
        ],
        username: [
          { required: true, message: "请输入账号", trigger: "blur" }],
        usable: [
          { required: true, message: "请选择状态", trigger: "change" },
        ],
         deptId: [
          { required: true, message: "所在省市县（区）不能为空", trigger: "change" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" }],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      const params = Object.assign(this.listQuery, this.page);
      account.getuserList(params).then((response) => {
        this.tableData = response.data.records;
        this.totalElements = response.data.total;
        this.page.pageNumber = response.data.current;
        this.page.pageSize = response.data.size;
      });
    },
    //获取可用角色列表
    getRoleList() {
      account.gefindByTenantId().then((response) => {
        let roleList = response.data;
        // let roleArr = roleList.shift()
        this.roleList = roleList;
      });
    },
    //获取机构列表
    getjiegouList() {
      getMechanismList().then(res => {
         this.lists = arrayToTree(res.data, {
                    parentProperty: 'parentId',
                    customID: 'id'
                  });
      });
    },
    //查询
    handleFilter() {
      this.page.pageNumber = 1;
      this.getList();
    },
    // 增加账户
    addaccount() {
      this.clearForm()
      this.dialogCarInfoVisible = true;
      this.pictureShow = false
      this.AccountUpdat= false
      this.typeRole = 0
      this.updateTitle = "增加用户";
      this.getRoleList();
      this.getjiegouList();
    },
     //清空表单
    clearForm(){
      this.fileList = []
      for(let key in this.ruleForm){
         this.ruleForm[key]  = ''
     }
    },
    //确认增加
    onSubmit() {
       const deptIdArr = this.ruleForm.deptId.toString();
       this.ruleForm.deptId = deptIdArr.substring(deptIdArr.lastIndexOf(",")+1)
        this.$refs.ruleForm.validate((valid) => {
        if (valid) {
        if (this.typeRole == 1) {
        //修改
        let updateDate = {
          deptId: this.ruleForm.deptId,
          id: this.jueseId,
          name: this.ruleForm.name,
          roleId: this.ruleForm.roleIds,
          usable: this.ruleForm.usable,
          phone: this.ruleForm.phone,
          email: this.ruleForm.email,
          idCard: this.ruleForm.idCard,
          gender: this.ruleForm.gender,
          photo: this.ruleForm.photo, 
        };
        account.updateUser(updateDate).then((res) => {
          if (res.status == 200) {
            this.dialogCarInfoVisible = false;
            this.fileList = []
            this.getList();
            this.$notify({
              title: "提示",
              message: "修改成功",
              type: "success",
              duration: 2000,
            });
          } else {
            this.$message({
              showClose: true,
              message: res.msg,
              type: "error",
            });
          }
        });
      } else {
         let params = {...this.ruleForm};
           const passWord = crypto.encrypt(params.password);
           params.password = passWord;
        account.addAccount(params).then((res) => {
          if (res.status == 200) {
            this.dialogCarInfoVisible = false;
            this.fileList = []
            this.getList();
            this.$notify({
              title: "提示",
              message: "新增成功",
              type: "success",
              duration: 2000,
            });
          } else {
            this.$message({
              showClose: true,
              message: res.msg,
              type: "error",
            });
          }
        });
      }
        } else {
          return false;
        }
      });
    },
    //重置密码
    resetButton(scope) {
      this.scopeId = scope.id;
      this.centerDialogVisible = true;
    },
    resetBut() {
      account.resetPassword(this.scopeId).then((res) => {
        if (res.status == 200) {
          this.centerDialogVisible = false;
          // this.getList();
          this.$notify({
            title: "提示",
            message: "重置密码成功",
            type: "success",
            duration: 2000,
          });
        } else {
          this.$message({
            showClose: true,
            message: res.msg,
            type: "error",
          });
        }
      });
    },
    // 修改
    Modify(scope, typeRole) {
      this.jueseId = scope.id; //用户id
      this.typeRole = typeRole;
      this.dialogCarInfoVisible = true;
      this.AccountUpdat= true
      this.updateTitle = "修改用户";
      this.picture = "更换头像"
      this.pictureShow = true
      this.menuIds = [];
      this.ruleForm.roleIds = [];
      this.getRoleList();
      this.getjiegouList();
      scope.roles.forEach((item, index) => {
        this.ruleForm.roleIds.push(item.id);
      });
      this.menuIds.push(scope.deptId);
      this.ruleForm.name = scope.name;
      this.ruleForm.username = scope.username;
      this.ruleForm.usable = scope.usable?.toString();
      this.ruleForm.deptId = scope.deptId;
      this.ruleForm.phone = scope.phone;
      this.ruleForm.email = scope.email;
      this.ruleForm.idCard = scope.idCard;
      this.ruleForm.gender = scope.gender?.toString();
      this.userPhoto = scope.photo
    },
    //禁用按钮
    disablebtn(scope) {
      if (scope.usable == "1") {
        this.$confirm("禁用该账户,相关账号将不能登陆, 是否继续?", "角色状态", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            account.switchState(scope.id).then((res) => {
              if (res.status == 200) {
                this.$notify({
                  title: "提示：",
                  message: "禁用账户成功",
                  type: "success",
                  duration: 2000,
                });
                this.getList();
              } else {
                this.$notify({
                  title: "提示：",
                  type: "error",
                  message: res.msg,
                  duration: 3000,
                });
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消禁用",
            });
          });
      } else {
        this.$confirm("启用该账户,相关账号将能够登陆, 是否继续?", "角色状态", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            account.switchState(scope.id).then((res) => {
              if (res.status == 200) {
                this.$notify({
                  title: "提示：",
                  message: "启用用成功",
                  type: "success",
                  duration: 2000,
                });
                this.getList();
              } else {
                this.$notify({
                  title: "提示：",
                  type: "error",
                  message: res.msg,
                  duration: 3000,
                });
              }
            });
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消启用",
            });
          });
      }
    },
    //删除按钮
    deleteButton(scope) {
      this.$confirm(
        "删除账号,拥有该账号将无法查看相关菜单页,是否继续?",
        "删除账号",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          account.deleteuser(scope.id).then((res) => {
            if (res.status == 200) {
              this.$notify({
                title: "提示：",
                message: "删除账号成功",
                type: "success",
                duration: 2000,
              });
              this.getList();
            } else {
              this.$notify({
                title: "提示：",
                type: "error",
                message: res.msg,
                duration: 3000,
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  getFile (options) {
    var that = this
    // 获取文件对象
    let file = options.raw
    //判断图片类型
    if (file.type == 'image/jpeg' || file.type == 'image/png' || file.type == 'image/JPG') {
     var  isJPG =  true
    } else {
     isJPG =  false
    }
   // 判断图片大小
    const isLt2M = file.size / 1024 / 1024 < 1
    if (!isJPG) {
      this.fileList = []
      this.$message.error('上传头像只能是 JPG/PNG/JPEG 格式!')
    }
    if (!isLt2M) {
      this.fileList = []
      this.$message.error('上传产品图片大小不能超过 1MB!')
    }
   // 创建一个HTML5的FileReader对象
    var reader = new FileReader();
    //创建一个img对象
   var  img = new Image();
    let filename = options.filename
    if (file) {
      reader.readAsDataURL(file)
    }
    if (isJPG && isLt2M) {
      reader.onload = (e) => {
      let base64Str = reader.result.split(',')[1]
       img.src = e.target.result
        // base64地址图片加载完毕后执行
            img.onload = function () {
                // 缩放图片需要的canvas（也可以在DOM中直接定义canvas标签，这样就能把压缩完的图片不转base64也能直接显示出来）
                var canvas = document.createElement('canvas');
                var context = canvas.getContext('2d');
                // 图片原始尺寸
                var originWidth = this.width;
                var originHeight = this.height;
                // 最大尺寸限制，可通过设置宽高来实现图片压缩程度
                var maxWidth = 100,
                    maxHeight = 100;
                // 目标尺寸
                var targetWidth = originWidth,
                    targetHeight = originHeight;
                // 图片尺寸超过最大尺寸的限制
                if(originWidth > maxWidth || originHeight > maxHeight) {
                    if(originWidth / originHeight > maxWidth / maxHeight) {
                        // 更改宽度，按照宽度限定尺寸
                        targetWidth = maxWidth;
                        targetHeight = Math.round(maxWidth * (originHeight / originWidth));
                    } else {
                        targetHeight = maxHeight;
                        targetWidth = Math.round(maxHeight * (originWidth / originHeight));
                    }
                }
                //对图片进行缩放
                canvas.width = targetWidth;
                canvas.height = targetHeight;
                // 清除画布
                context.clearRect(0, 0, targetWidth, targetHeight);
                // 图片压缩
                context.drawImage(img, 0, 0, targetWidth, targetHeight);
                /*第一个参数是创建的img对象；第二三个参数是左上角坐标，后面两个是画布区域宽高*/
                //压缩后的base64文件
                that.ruleForm.photo = canvas.toDataURL('image/jpeg', 0.9);
            }
     }
    }
  },
  },
  watch: {
    "listQuery.orgId": function () {
      this.getDataDropList();
    },
  },
};
</script>


<style lang="scss" scoped>
@import "~@/styles/mixin.scss";
@import "~@/styles/variables.scss";
::v-deep .el-dialog__body {
  overflow: auto;
  max-height: 60vh;
}
.box {
  padding: 0 15px;
}

.el-row {
  margin-bottom: 25px;
  &:last-child {
    margin-bottom: 0;
  }
}

.form-item {
  display: flex;
  font-size: 16px;

  > .label {
    margin: 0;
    line-height: 1;
    white-space: nowrap;
    padding-right: 12px;
  }
}
.btnnuma {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
}
.card {
  display: flex;
  justify-content: space-around;
  .tablebox {
    flex: 2;
    margin-right: 5px;
  }
  .jigou {
    flex: 2;
    height: 100%;
  }
}
.role-name-tag {
  margin-left: 5px;
  margin-bottom: 5px;
}
/* 去掉全选按钮 */
::v-deep .el-table .disabledCheck .cell .el-checkbox .el-checkbox__input{
    display: none !important; 
}
 
 ::v-deep .el-table .disabledCheck .cell::before{
    content: '选择';
    text-align: center;
    line-height: 37px;
}
.userImg{
  width: 50px;
  height: 50px;
  img{
    width: 100%;
    height: 100%;
  }
}
</style>
